<?php

class Pemesanan extends record {

    function __construct() {
        parent::__construct();
        $this->namaTabel = 'pemesanan';
    }
    function getMyOwnHandleOrder(){
        $str = "SELECT okr.kota AS kota_tujuan, c.nama AS nama_pemesan, pm.*,IFNULL(pd.subtotal_c,0)  AS subtotal 
        FROM pemesanan pm LEFT JOIN(
            SELECt pd.id_pesanan AS id_pem, SUM(pd.subtotal)AS subtotal_c FROM pesanan_detail pd GROUP BY pd.id_pesanan
            )pd ON pm.id_pemesanan = pd.id_pem
LEFT JOIN customer c ON c.id = pm.idcus
LEFT JOIN ongkir okr ON okr.id = pm.ongkir
WHERE pm.idadmin = '".$_SESSION['adminlogin']['id']."' ORDER BY pm.tanggal ASC";
$this->query($str);
return $this->execute();
}
function getPendingOrder(){
    $str = "SELECT okr.kota AS kota_tujuan, c.nama AS nama_pemesan, pm.*,IFNULL(pd.subtotal_c,0)  AS subtotal 
    FROM pemesanan pm LEFT JOIN(
        SELECt pd.id_pesanan AS id_pem, SUM(pd.subtotal)AS subtotal_c FROM pesanan_detail pd GROUP BY pd.id_pesanan
        )pd ON pm.id_pemesanan = pd.id_pem
LEFT JOIN customer c ON c.id = pm.idcus
LEFT JOIN ongkir okr ON okr.id = pm.ongkir
WHERE pm.status_pesan = 'TUNGGU_PEMBAYARAN' ORDER BY pm.tanggal ASC";
$this->query($str);
$dt = $this->execute();
   // var_dump($dt);
return isset($dt['result'])?$dt['result']:array();
}
function statusOrder($s){
    $re='';
    switch ($s) {
        case 'TUNGGU_PEMBAYARAN':
        $re ='Menunggu Pembayaran';
        break;
        case 'DITOLAK':
        $re='Ditolak';
        break;
        case 'PENGIRIMAN':
        $re = 'Dalam Pengiriman';
        break;
        case 'SELESAI':
        $re='Transaksi Selesai';
        break;
        default:
        $re='Tidak Diketahui';
        break;
    };
    return $re;
}
function buatComboStatus($chkVal){
    $stat  = array('TUNGGU_PEMBAYARAN','DITOLAK','PENGIRIMAN','SELESAI');
    $str = "";
    foreach ($stat as $value) {
        $ch = ($value==$chkVal)?" selected = 'selected' ":"";
        $str .="<option value='".$value."' ".$ch." >".$this->statusOrder($value)."</option>";
    }
    return $str;
}
function getListOrder($limit=null,$start=0,$status=null){
    $wh = array();
    if(isset($status) && strlen($status)>0){
        $wh['status']=$status;
    }
    $this->get('*',$wh);
    $ex  = $this->execute();
    $res= isset($ex['result'])?$ex['result']:array();
    $this->num_rows($wh);
    $exTotal = $this->execute();
    $total = $exTotal['success']==true?$exTotal['result'][0]['total']:0;
    return  array('result' =>$res ,'total'=>$total);
}
function getHistoriOrder(){
    $strQ = "SELECT  p.id  ,p.status_pesan
    ,p.id_pemesanan ,p.tanggal ,p.nama_penerima, o.kota AS kota_penerima, p.biaya_ongkir
    ,p.telepon AS telepon_penerima,p.alamat AS alamat_penerima,p.email AS email_penerima
    ,p.pesan_tambahan ,r.atasnama ,r.bank ,r.norek ,r.cabang ,c.nama ,c.telepon ,c.email
    FROM pemesanan p 
    LEFT JOIN rekening r ON p.rekening = r.id
    LEFT JOIN ongkir o ON o.id = p.ongkir
    LEFT JOIN customer c ON c.id = p.idcus 
    WHERE p.idcus='".(isset($_SESSION['userlogin']['id'])?$_SESSION['userlogin']['id']:'')."'";
    $this->query($strQ);
    return $this->execute();
}

function getDataPesan($idPesanan,$idAdmin=null,$forProses =null) {
    $strIDCUS = '';
    if(!isset($forProses)){
        $strIDCUS .= " AND p.idcus='".(isset($_SESSION['userlogin']['id'])?$_SESSION['userlogin']['id']:'')."' ";
    }
    if(isset($idAdmin) && strlen($idAdmin)>0){
        $strIDCUS .=" AND p.idadmin ='".$idAdmin."' ";
    }
    $strQ = "SELECT  p.id  ,p.status_pesan,p.ket_admin
    ,p.id_pemesanan ,p.tanggal ,p.nama_penerima, o.kota AS kota_penerima, p.biaya_ongkir
    ,p.telepon AS telepon_penerima,p.alamat AS alamat_penerima,p.email AS email_penerima
    ,p.pesan_tambahan ,r.atasnama ,r.bank ,r.norek ,r.cabang ,c.nama ,c.telepon ,c.email
    FROM pemesanan p 
    LEFT JOIN rekening r ON p.rekening = r.id
    LEFT JOIN ongkir o ON o.id = p.ongkir
    LEFT JOIN customer c ON c.id = p.idcus 
    WHERE p.id_pemesanan = '" . $idPesanan . "'".$strIDCUS;
    $this->query($strQ);
    $ec = $this->execute();
    if ($ec['success'] == true && $ec['total'] > 0) {
        $dtR = $ec['result'][0];
        $ret['success']=true;
        $ret['id'] = $dtR['id'];
        $ret['id_pemesanan'] = $dtR['id_pemesanan'];
        $ret['tanggal'] = $dtR['tanggal'];
        $ret['nama_penerima'] = $dtR['nama_penerima'];
        $ret['telepon_penerima'] = $dtR['telepon_penerima'];
        $ret['alamat_penerima'] = $dtR['alamat_penerima'];
        $ret['email_penerima'] = $dtR['email_penerima'];
        $ret['pesan_tambahan'] = $dtR['pesan_tambahan'];
        $ret['kota_penerima'] = $dtR['kota_penerima'];
        $ret['biaya_ongkir'] = $dtR['biaya_ongkir'];
        $ret['atasnama'] = $dtR['atasnama'];
        $ret['bank'] = $dtR['bank'];
        $ret['norek'] = $dtR['norek'];
        $ret['cabang'] = $dtR['cabang'];
        $ret['nama'] = $dtR['nama'];
        $ret['telepon'] = $dtR['telepon'];
        $ret['email'] = $dtR['email'];
        $ret['ket_admin'] = $dtR['ket_admin'];
        $ret['status_pesan'] = $dtR['status_pesan'];
    } else {
        $ec['success'] = false;
        $ec['error_msg'] = isset($ec['error_msg'])?$ec['error_msg']:'Data Tidak Ada';
        $ret = $ec;
    };
    $dataDet  = '';
    if ($ec['success'] == true) {
        $strDetail = "SELECT  p.nama ,p.gambar ,p.keterangan ,pd.harga AS harga_awal 
        ,pd.harga-(pd.harga*(pd.diskon/100)) AS harga_bayar ,pd.diskon
        ,pd.jumlah_buy ,k.nama AS kategori
        FROM pesanan_detail pd 
        LEFT JOIN produk p ON pd.id_produk = p.id
        LEFT JOIN kategori k ON k.id = p.idkategori
        WHERE pd.id_pesanan='" . $idPesanan . "'";
        $this->query($strDetail);
        $det = $this->execute();
        if ($det['success'] == false) {
            $dataDet = array();
        } else {
            $dataDet = $det['result'];
        }
    }
    return array('header' => $ret, 'detail' => $dataDet);
}

function addDetail($arrAdd) {
    $this->namaTabel = 'pesanan_detail';
    $this->create($arrAdd);
}

function getLastID() {
    $this->get('id', array(), 1, 0, 'id', 'DESC');
    $e = $this->execute();
    if ($e['success'] == true) {
        return $e['result'][0]['id'];
    } else {
        return false;
    }
}

function sendOrderMail($idPemesanan,$email) {
    $subject="Detail Pemesanan - ".MAINSITENAME;
    $message = '<html>
    <head>
    <title>Order Nomor: '.$idPemesanan.'</title>

    <link rel="stylesheet" type="text/css" href="'.BASEURL.'css/report.css">
    <link rel="stylesheet" type="text/css" href="'.BASEURL.'css/isi.css">
    <style>
    body{
        text-align:center;
    }
    </style>
    </head>
    <body>
    <h4>Detail Pemesanan</h4>
    <div class="frame_table_order">
    <table width="100%" cellpadding="5" cellspacing="0" border="1" style="border-collapse:collapse">
    <thead>
    <tr align="center" valign="middle" bgcolor="#CCCCCC">
    <th>No</th>
    <th>Gambar</th>
    <th>Nama</th>
    <th>Harga</th>
    <th>Qty</th>
    <th>Subtotal</th>
    </tr>
    </thead>
    <tbody>';
    $total = 0;
    $dtS = $this->getDataPesan($idPemesanan);
    if (count($dtS['detail']) == 0) {
        $message .= '<tr><td colspan="7">(belum ada item)</td></tr>';
    } else {
        $no=1;            
        foreach ($dtS['detail'] as $k=>$value){
            $hrg = $value['diskon']>0?($value['harga_awal']-($value['harga_awal']*($value['diskon']/100))):$value['harga_awal'];
            $message .= '
            <tr> 
            <td>'.$no++.'</td>
            <td><img style="width:50px;height:50px" src="'.BASEURL.'produk/'.$value['gambar'].'"/></td>
            <td>Nama</td>
            <td style="text-align: right">'.(($value['diskon']>0)?"<span style='text-decoration:line-through;color:red;font-size:small'>
                ".number_format($value['harga_awal'],0,'.',',')."
                </span><br/>":"").number_format($hrg,0,'.',',').'
            <td>'.$value['jumlah_buy'].'</td>
            <td style="text-align: right">';

            $total +=$hrg*$value['jumlah_buy'];
            $message .= number_format($hrg*$value['jumlah_buy'],0,'.',',').'</td></tr>';
        }
    };

    $message .= '</tbody>
    <tfoot>
    <tr>
    <th colspan="6" style="text-align: right">Total: <input style="text-align:right" type="text" 
    class="option" disabled="disabled" value="'."Rp. ".number_format( $total,0,'.',',').'" />
    </th>
    <th style="text-align: right">
    </th>            
    </tr>        
    </tfoot>
    </table>';
    $message .= "<h2>Biaya Pengiriman Ke ".$dtS['header']['kota_penerima'].':'.$dtS['header']['biaya_ongkir'].'</h2>';
    $message .="<p>Total Pembayaran:</p>";
    $totalByrnya = number_format(($dtS['header']['biaya_ongkir']+$total),0,',','.');
    $message .="<h3>".$totalByrnya."</h3>";
    $message .='<p>Silahkan Transfer Ke </p>';
    $message .= '<h3>'.$dtS['header']['bank'].'('.$dtS['header']['norek'].')</h3>';
    $message .= '<p>dengan Pesan Referensi</p>';
    $message .= '<h3>INV '.$idPemesanan.'</h3>';
    $message .= '<p>Selambat-lambatnya 3 hari setelah pemesanan ini dilakukan</p>';
    $message .='</body></html>';
    $headers = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= 'To: <' . $email . '>' . "\r\n";
    $headers .= 'From: '.MAINSITENAME.' <' . MAILUTAMA . '>' . "\r\n";
    mail($email, $subject, $message, $headers);
} 
function buatNoTrans() {
    $ret = "JMC." . date('Y') . "." . date('m') . ".";
    $this->get('id_pemesanan', array(), 1, 0, 'id', 'DESC', 'id_pemesanan LIKE "' . $ret . '%"');
    $d = $this->execute();
    if ($d['success'] == false || ($d['success'] == true && $d['total'] == 0)) {
        $ret .="001";
    } else {
        $dt = $d['result'][0]['id_pemesanan'];
        $arrE = explode('.', $dt);
        $ur = (int) (isset($arrE[3]) ? $arrE[3] : 0) + 1;
        switch (strlen($ur)) {
            case 1:
            $ret .="00" . $ur;
            break;
            case 2:
            $ret .="0" . $ur;
            break;
            case 3:
            $ret .=$ur;
            break;
            default :
            $ret .="001";
            break;
        }
    };
    return $ret;
}

}

$objPemesanan = new Pemesanan();